<?php
/*
数据库操作类。作用如下：
1.所有的数据库操作都是通过这个类进行操作;
2.目前已有的函数insert(),update(),delete(),select(),existTable(),sqlQuery();
3.初步实现防SQL注入;(以后得加强升级)
4.本类使用Java实例化思维，只需通过调用getInstance()即可返回一个实例化后的对象;
5.以后可能进行大改动，主要针对速度的优化。接口不会改变，以保证model层访问良好。
*/


include_once dirname(dirname(dirname(__FILE__)))."/config/app.config.php";
final class Database{
	protected $dbAddress;    //数据库地址
	protected $dbAccount;    //数据库用户名
	protected $dbPwd;        //数据库密码
	protected $dbName;            
	protected $conn;
	public $result;
	public $resultNumber;
	protected $debug;
	
	static function getInstance() {
		static $instance = array();
		if (!$instance) {
			$instance[0] = new Database;
		}
		return $instance[0];
	}
	
	
	public function __get($name){
		return $this->$name;
	}
	//构造函数，连接数据库
	function __construct(){
			$this->dbAddress=config::$dbAddress;
			$this->dbAccount=config::$dbAccount;
			$this->dbPwd=config::$dbPwd;
			$this->dbName=config::$dbName;
			$this->debug=config::$debug;
			
			$this->conn=mysql_connect($this->dbAddress, $this->dbAccount, $this->dbPwd ) or die("Could connect to mysql server!");   
			mysql_select_db($this->dbName)or die("Could connect to mysql db!");
			mysql_query("SET NAMES utf8")or die("Wrong:SET NAMES utf8");
			mysql_query("ALTER DATABASE `".$this->dbName."` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci");
	}
	//析构函数
	function __destruct(){
		mysql_close($this->conn);
	}
	//SQL语句请求
	function sqlQuery($sql){
		if($this->debug)
			Debug::getInstance()->newSql($sql);
		return mysql_query($sql);
	}
	//是否存在表$table
	function getTableName(){
		$result=$this->sqlQuery("SHOW TABLES FROM ".$this->dbName);
		$count=mysql_num_rows($result);
		$result1=array();
		while($row=mysql_fetch_row($result))
			array_push($result1,$row[0]);
		return $result1;
	}
	//插入语句
	function insert($table,$name,$value){
		$namestring='';
		$valuestring='';
		if(count($name)!=count($value))
			return Error;
		for($i=0;$i<count($name);$i++){
			$namestring.='`'.$name[$i].'`';
			$valuestring.='\''.$this->dowith_sql($value[$i]).'\'';
			if($i+1<count($name)){
				$namestring.=',';
				$valuestring.=',';
			}
		}
		$sql="INSERT INTO `$table` ($namestring) VALUE ( $valuestring );";
		return $this->sqlQuery($sql);
	}
	//构建条件语句
	function constructCondition($condition){
		$sql='';
		if(is_array($condition)){
			$sql.='`id` in(';
			for($i=0;$i<count($condition);$i++){
				$sql.=$condition[$i];
				if($i+1<count($condition))
					$sql.=',';
			}
			$sql.=')';
		}else if(is_int($condition)){
			$sql.="`id`=$condition";
		}else if(is_string($condition)){
			$sql.=$condition;
		}
		return $sql;
	}
	//删除语句
	function delete($table,$condition){
		$sql="DELETE FROM `$table` WHERE ";
		$sql.=$this->constructCondition($condition).';';
		return $this->sqlQuery($sql);
	}
	//更新语句
	function update($table,$condition,$name,$value){
		$sql="UPDATE `$table` SET ";	
		$namestring='';
		$valuestring='';
		if(is_array($name)){
			if(count($name)!=count($value))
				return Error;
			for($i=0;$i<count($name);$i++){
				$sql.='`'.$this->dowith_sql($name[$i]).'`=\''.$this->dowith_sql($value[$i]).'\'';
				if($i+1<count($name)){
					$sql.=',';
				}
			}
		}else if (is_string($name)){
			$sql.='`'.$name.'`=\''.$value.'\'';
		}
		$sql.=' WHERE '.$this->constructCondition($condition).';';
		return $this->sqlQuery($sql);
	}
	//查询语句
	function select($table,$name,$condition=NULL){
		$sql='SELECT ';
		if(is_array($name)){
			for($i=0;$i<count($name);$i++){
				$sql.='`'.$this->dowith_sql($name[$i]).'`';
				if($i+1<count($name))
					$sql.=',';
			}
		}else{
			$sql.=''.$name.'';
		}
		$sql.=' FROM ';
		if(is_array($table)){
			for($i=0;$i<count($table);$i++){
				$sql.="`$table[$i]`";
				if($i+1<count($table))
					$sql.=',';
			}
		}else{
			$sql.="`$table`";
		}
		if($condition!=NULL){
			$sql.=' WHERE ';
			$sql.=$this->constructCondition($condition).';';
		}
		$result1=$this->sqlQuery($sql);
		$this->resultNumber=@mysql_num_rows($result1);
		if($this->resultNumber!=0){
			$i=1;		
			while($row=mysql_fetch_row($result1)){
				$j=0;
				$this->result[$i]=array();
				while($j<mysql_num_fields($result1)){
					$meta=mysql_fetch_field($result1,$j);
					$this->result[$i][$this->show_sql_keyword($meta->name)]=$this->show_sql_keyword($row[$j]);
					$j++;
				}
				$i++;
			}
			return $this->result;
		}else{
			return NULL;
		}
	}
	
	private function dowith_sql($str){
	   $refuse_str="and|or|select|update|from|where|order|by|*|delete|'|insert|into|values|create|table|database";
	   $arr=explode("|",$refuse_str);
	   for($i=0;$i<count($arr);$i++)
	   {
		 $replace="[".$arr[$i]."]";
		 $str=str_replace($arr[$i],$replace,$str);
	   }
	   return $str;
	}
	
	private function show_sql_keyword($str){
	   $refuse_str="and|or|select|update|from|where|order|by|*|delete|'|insert|into|values|create|table|database";
	   $arr=explode("|",$refuse_str);
	   for($i=0;$i<count($arr);$i++)
	   {
		 $replace="[".$arr[$i]."]";
		 $str=str_replace($replace,$arr[$i],$str);
	   }
	   return $str;
	}
	
}
	
class foreignKey
{
	
	
}
	


?>